package ink.onei.common.api.cloud;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import ink.onei.common.aop.Tag;
import ink.onei.common.core.domain.AjaxResult;
import ink.onei.common.exception.OperateException;
import ink.onei.common.utils.file.FileUtils;
import ink.onei.common.utils.uuid.IdUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;

import static ink.onei.common.constant.Constants.*;

/**
 * @Author: nekotako
 * @Description: TODO
 * @Date: 27/01/2024 14:31 Saturday
 */

public class CloudStorage {

    //Let's create S3 client
    private static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(CLOUD_ACCESS_KEY, CLOUD_SECRET_KEY);
    public static final AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds))
            .withRegion(Regions.AP_NORTHEAST_2)
            .build();

    /**
     * Creates and return a new PutObjectRequest object
     *
     * @param key 文件地址
     * @param file 本地文件对象
     * @return PutObjectRequest 对象
     */
    public static PutObjectRequest getUploadRequest(String bucketName, String key, File file) {
        // 设置文件并设置公读
        PutObjectRequest request = new PutObjectRequest(bucketName, key, file);
        request.withCannedAcl(CannedAccessControlList.PublicRead);
        return request;
    }

    /**
     * 上传文件方法
     * @param type 文件类型
     * @param property 文件子类型
     * @param file 本地文件对象 名称需要为UUID格式
     * @return 成功返回true 失败返回false
     */
    public static boolean uploadFile(String type, String property, File file) {
        if (type == null || property == null || file == null) throw new OperateException("Arguments not specified");
        else if (!IdUtils.isValidUUID(FilenameUtils.getBaseName(file.getName())))
            throw new OperateException("You must provide a valid UUID for the file name");

        PutObjectRequest uploadRequest = CloudStorage.getUploadRequest(BUCKET_NAME,type +"/" + property + "/" + file.getName(), file);
        try {
            CloudStorage.s3Client.putObject(uploadRequest);
        } catch (AmazonServiceException e) {
            AjaxResult.error(e.getMessage());
            return false;
        }
        return true;
    }

}
